package main

import (
	"log"
	"os"
	"os/exec"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	wechatMainPath := "./rpc/wechat/wechat.go"
	wechatConfigFile := "./rpc/wechat/etc/wechat.yaml"
	// 执行 WeChat RPC 服务
	err := runCommand("go", "run", wechatMainPath, "-f", wechatConfigFile)
	if err != nil {
		log.Fatalf("WeChat RPC service failed to start: %v", err)
	}

	transformMainPath := "./rpc/transform/transform.go"
	transformConfigFile := "./rpc/transform/etc/transform.yaml"
	// 执行 Transform RPC 服务
	err = runCommand("go", "run", transformMainPath, "-f", transformConfigFile)
	if err != nil {
		log.Fatalf("Transform RPC service failed to start: %v", err)
	}

	// 等待 rpc 服务启动
	time.Sleep(time.Second)

	apiMainPath := "./api/vxopen.go"
	apiConfigFile := "./api/etc/vxopen-api.yaml"
	//// 执行 API 服务
	err = runCommand("go", "run", apiMainPath, "-f", apiConfigFile)
	if err != nil {
		log.Fatalf("Transform RPC service failed to start: %v", err)
	}

	// 等待中断信号以优雅地退出
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	<-sigs

	log.Println("Shutting down services...")
}

// runCommand 函数用于在指定目录下执行命令
func runCommand(command string, args ...string) error {
	cmd := exec.Command(command, args...)

	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// 执行但不会等待完成
	if err := cmd.Start(); err != nil {
		return err
	}

	// 等待命令完成
	go func() {
		if err := cmd.Wait(); err != nil {
			log.Printf("Command finished with error: %v\n", err)
		}
	}()

	return nil
}
